const router = require('koa-router')()
const request = require('superagent')

// require('superagent-proxy')(request)

const IP_POOL = [
  '192.241.254.131:3128',
  '192.241.254.131:80',
  '174.120.70.232:80',
  '203.135.80.25:8080',
  '210.242.179.118:80'
]

router.get('/', async (ctx, next) => {
  await ctx.render('index', {
    title: 'Hello Koa 2!'
  })
})

router.get('/schedule.aspx', async (ctx, next) => {
  const html = await http('http://bet.hkjc.com/football/schedule/schedule.aspx?lang=CH' || ctx.query.uri)
  ctx.body = html;
})

router.get('/data', async (ctx, next) => {
  const data = await http('http://bet.hkjc.com/football/getJSON.aspx', ctx.query)
  ctx.body = data
})

router.get('/ContentServer/jcbw/cmc/userxml/sbdata_userMenuC.xml', async(ctx, next) => {
  const  data = await http('http://bet.hkjc.com/ContentServer/jcbw/cmc/userxml/sbdata_userMenuC.xml')
  ctx.body = data
})

router.get('*', async (ctx, next) => {
  const html = await http(`http://bet.hkjc.com${ctx.params["0"]}`, ctx.query)
  ctx.body = html;
})

function http(uri, query) {
  console.log('请求：' + uri)
  return new Promise((resolve, reject) => {
    request
      .get(uri)
      .query(query)
      .set('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36')
      // .proxy(`http://${IP_POOL[ip]}`)
      .then(res => {
        resolve(res.text)
      })
      .catch(error => reject(error))
  })
}

module.exports = router
